<template>
  <el-container>
    <el-header>
      <h2>纠违数据统计</h2>
    </el-header>
    <el-main>
      <div v-if="source && source.length>0">
        <chart-view
          v-for="(config,index) in conditions"
          :key="index"
          :source="source"
          :config="config"
          :index="index"
          @remove="handleRemove"
          @create="handleCreate"
          @modify="handleModify"
        />
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { defaultConditions } from "./defaults";
import ChartView from "./ChartView";
export default {
  components: {
    ChartView,
  },
  data() {
    return {};
  },
  computed: {
    conditions() {
      return this.$store.state.summary.inspectSummary.conditions;
    },
    source() {
      return this.$store.state.summary.inspectSource;
    },
  },

  methods: {
    handleCreate(payload) {
      let tmp = JSON.parse(JSON.stringify(this.conditions));
      tmp.splice(payload.index, 0, payload.config);
      this.saveConditions([]);
      this.$nextTick(() => {
        this.saveConditions(tmp);
      });
    },
    handleModify(payload) {
      let tmp = JSON.parse(JSON.stringify(this.conditions));
      tmp.splice(payload.index, 1, payload.config);
      this.saveConditions([]);
      this.$nextTick(() => {
        this.saveConditions(tmp);
      });
    },
    handleRemove(index) {
      if (this.conditions.length === 1) {
        this.$notify.error({
          title: "(⊙o⊙)…)",
          message: "只剩最后一个图表了",
        });
      } else {
        this.$notify.success({
          title: "已删除",
          message: "图表 #" + this.conditions[index].title + "#",
        });
        let tmp = JSON.parse(JSON.stringify(this.conditions));
        tmp.splice(index, 1);
        this.saveConditions([]);
        this.$nextTick(() => {
          this.saveConditions(tmp);
        });
      }
    },
    saveConditions(data) {
      this.$store.commit("summary/SAVE_INSPECT", {
        key: "conditions",
        data: null,
      });
      this.$nextTick(() => {
        this.$store.commit("summary/SAVE_INSPECT", {
          key: "conditions",
          data: data,
        });
      });
    },
  },
  mounted() {
    if (this.conditions.length === 0) {
      this.saveConditions(defaultConditions);
    }
  },
};
</script>